package com.work.controller;

import com.google.gson.Gson;
import com.work.bean.Hw;
import com.work.bean.Student;
import com.work.bean.Teacher;
import com.work.bean.User;
import com.work.dao.HwAttachDao;
import com.work.dao.HwDao;
import com.work.dao.HwStuAttachDao;
import com.work.dao.impl.HwAttachDaoImpl;
import com.work.dao.impl.HwDaoImpl;
import com.work.dao.impl.HwStuAttachDaoImpl;
import com.work.dto.TeacherHw;
import com.work.service.HwAttachService;
import com.work.service.HwService;
import com.work.service.StudentService;
import com.work.service.impl.HwAttachServiceImpl;
import com.work.service.impl.HwServiceImpl;
import com.work.service.impl.StudentServiceImpl;
import com.work.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class HwServlet extends BaseServlet {
    HwDao hwDao = new HwDaoImpl();
    HwService hwService = new HwServiceImpl();
    HwAttachService hwAttachService = new HwAttachServiceImpl();
    StudentService studentService = new StudentServiceImpl();
    HwAttachDao hwAttachDao = new HwAttachDaoImpl();
    protected void queryHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        List<Hw> hws = hwService.queryHw();
        req.setAttribute("hws",hws);
        if(((User)req.getSession().getAttribute("user")).getType().equals("2")){
            req.getRequestDispatcher("/pages/student/student_submit.jsp").forward(req, resp);
        }else if(((User)req.getSession().getAttribute("user")).getType().equals("1")) {
            int teacher_id = WebUtils.parseInt(req.getParameter("id"),0);
            List<Hw> thws = hwDao.queryHwByTeacherId(teacher_id);
            req.setAttribute("thws",thws);
            req.getRequestDispatcher("/pages/teacher/teacher_managent.jsp").forward(req, resp);
        }else {
                req.getRequestDispatcher("/pages/admin/admin_hw.jsp").forward(req, resp);
            }
        }


    protected void queryHwStu(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        List<TeacherHw> tHws = hwService.queryTeacherHw();
        req.setAttribute("tHws",tHws);
        if(((User) req.getSession().getAttribute("user")).getType().equals("2")) {
            req.getRequestDispatcher("/pages/student/student_download.jsp").forward(req, resp);
        }else {
            req.getRequestDispatcher("/pages/admin/materrial/admin_materrial_teacher.jsp").forward(req, resp);
        }
    }

    protected void queryHwById(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Hw hw = hwService.queryHwById(id);
        req.setAttribute("hw", hw);
        req.getRequestDispatcher("/pages/admin/admin_hw.jsp").forward(req, resp);
    }

    protected void saveHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException, ParseException {
        String url = null;
        String title = "";
        String describe = "";
        String end =  "";

        if (ServletFileUpload.isMultipartContent(req)) {
            // 创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创建用于解析上传数据的工具类ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            servletFileUpload.setHeaderEncoding("UTF-8");
            try {
                // 解析上传的数据，得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // 循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        if(fileItem.getFieldName().equals("title")){
                            title = fileItem.getString("UTF-8");
                        }else if(fileItem.getFieldName().equals("describe")){
                            describe = fileItem.getString("UTF-8");
                        }else if(fileItem.getFieldName().equals("end_time")){
                            end = fileItem.getString("UTF-8");
                        }
                        // 普通表单项
                        System.out.println("表单项的name 属性值：" + fileItem.getFieldName());
                        // 参数UTF-8.解决乱码问题
                        System.out.println("表单项的value 属性值：" + fileItem.getString("UTF-8"));
                    } else {
                        // 上传的文件
                        System.out.println("表单项的name 属性值：" + fileItem.getFieldName());
                        System.out.println("上传的文件名：" + fileItem.getName());
                        url = fileItem.getName();
                        fileItem.write(new File("d:\\work\\teacher\\" + fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(end);
        Date time = sf.parse(end);
        Teacher teacher = (Teacher) req.getSession().getAttribute("teacher");
        Date end_time = new java.sql.Date(time.getTime());
        System.out.println(url);
        hwService.saveHw(new Hw(null, teacher.getId(), title, describe, end_time),teacher,url);
        req.getRequestDispatcher("/pages/teacher/teacher.jsp").forward(req, resp);
    }

    protected void updateHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        Hw hw = hwService.queryHwById(id);
        req.setAttribute("hw", hw);
        req.getRequestDispatcher("/pages/admin/admin_hw.jsp").forward(req, resp);
    }

    protected void deleteHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        hwService.deleteHw(id);
        hwAttachDao.deleteHwAttach1(id);
        resp.sendRedirect(req.getContextPath() + "/HwServlet?action=queryHwStu");
    }

    protected void downloadHw(HttpServletRequest req, HttpServletResponse resp) throws
            ServletException, IOException {

        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        System.out.println(id);
        String url = hwAttachService.queryHwAttachByHwId(id).getUrl();
        String fileName=new String(url.getBytes("iso8859-1"), "UTF-8");
        // 上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
        String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        // 得到要下载的文件
        File file = new File("D:\\work\\teacher\\" + url);
        // 如果文件不存在
        if (!file.exists()) {
            req.setAttribute("message", "您要下载的资源已被删除！！");
            req.getRequestDispatcher("/pages/student/student_download.jsp").forward(req, resp);
            return;
        }
        // 设置响应头，控制浏览器下载该文件
        // 设置文件MIME类型
        resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(url, "UTF-8"));
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();
        byte buffer[] = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        in.close();
        out.close();
//        req.getRequestDispatcher("/pages/student/student_download.jsp").forward(req, resp);
    }
}
